﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;
using word=Microsoft.Office.Interop.Word;
using System.Reflection;
using System.IO;
using System.Text.RegularExpressions;
using System.Data;
using System.Data.SQLite;
using Microsoft.Win32;
namespace ListOfTale
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        #region Поля, св-ва, инициализация
        private ObservableCollection<Book> _Books = new ObservableCollection<Book>();
        public ObservableCollection<Book> Books { get { return _Books; } set { _Books = value; FirePropertyChanged("Books"); } }

        private bool _IsChanged = false;
        public bool IsChanged { get { return _IsChanged; } set { _IsChanged = value; FirePropertyChanged("IsChanged"); } }
        public MainWindow()
        {
            InitializeComponent();
            Savebtn.DataContext = this;
        }
 
        private void FirePropertyChanged(string par)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(par));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        #region Загрузка в базу

        private int AddAuthor(string Name)
        {
            var ata = new TalesDataSetTableAdapters.AuthorTableAdapter();
            int id= Convert.ToInt32( ata.GetNewId());
            ata.Insert("", Name, id);
            RefreshAut();
            return id;
        }

        private int addKey(string key)
        {
            var keys = new TalesDataSetTableAdapters.KeysTableAdapter();
            int idkey = Convert.ToInt32(keys.GetNewID());
            keys.Insert(key, idkey);
            RefreshKeys();
            return idkey;
        }

        private void Addbtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                int keyid = 0;
                if (keyComb.SelectedValue != null)
                {
                    keyid=((keyComb.SelectedValue as System.Data.DataRowView).Row as TalesDataSet.KeysRow).IdKey;
                }
                else
                {
                    keyid = addKey(keyComb.Text);
                }
                int autid = 0;
                if (AuthComb.SelectedValue != null)
                {
                    autid = ((AuthComb.SelectedValue as System.Data.DataRowView).Row as TalesDataSet.AuthorRow).AuthorId;
                }
                else
                {
                    autid = AddAuthor(AuthComb.Text);
                }
                var taleta = new TalesDataSetTableAdapters.TaleTableAdapter();
                int newid =Convert.ToInt32( taleta.GetNewID());
                taleta.Insert(Convert.ToInt32(Year.Text), keyid, Convert.ToInt32(Printing.Text), NameTale.Text, newid, autid, "");
                RefreshFirstsTales();
                ClearFields();
            }
            catch (Exception ex)   { MessageBox.Show(ex.Message); }
        }

        private void ClearFields()
        {
            NameTale.Text = "";
            Printing.Text = "";
        }
        #endregion

        #region Редактирование
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("Вы уверены? Потом можно и не восстановить", "", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                TalesDataSetTableAdapters.TaleTableAdapter ta = new TalesDataSetTableAdapters.TaleTableAdapter();
                if (taleDataGrid.SelectedValue != null)
                {
                    var originalid = ((taleDataGrid.SelectedValue as DataRowView).Row as TalesDataSet.TaleRow).IdTale;

                    if (ta.Delete(originalid) == 1)
                    {
                        RefreshFirstsTales();
                    }
                    else
                    {
                        MessageBox.Show("Ничего не удалено");
                    }
                }
                else { MessageBox.Show("Нужно выбрать строку для удаления"); }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ListOfTale.TalesDataSet talesDataSet = ((ListOfTale.TalesDataSet)(this.FindResource("talesDataSet")));

            TalesDataSetTableAdapters.TaleTableAdapter ta = new TalesDataSetTableAdapters.TaleTableAdapter();
            ta.Update(talesDataSet.Tale);
            IsChanged = false;
        }
        #endregion

        #region Экспорт в word
        private void ExportToWord()
        {
            word.Application app = null;
            word.Document doc = null;
            try
            {
                ListOfTale.TalesDataSet talesDataSet = ((ListOfTale.TalesDataSet)(this.FindResource("talesDataSet")));
                var tales = talesDataSet.Tale;
                var kes = talesDataSet.Keys;
                var auts = talesDataSet.Author;
                app = new word.Application();

                app.Visible = true;
                object template = Missing.Value;
                int cur = 0;

                object newTemplate = Missing.Value;

                object documentType = Missing.Value;
                doc = app.Documents.Add(ref template, ref newTemplate, ref documentType);

                foreach (var b in tales.GroupBy(el => el.Year).OrderBy(el => el.Key))
                {
                    doc.Words.Last.InsertAfter(b.Key.ToString() + "\n");
                    object start = cur;
                    object end = cur + b.Key.ToString().Length;
                    word.Range r = doc.Range(start, end);
                    r.Bold = 1;
                    cur += b.Key.ToString().Length + 1;
                    foreach (var bb in b.GroupBy(el => el.GroupId).OrderBy(el => el.Key))
                    {
                        string Group = kes.Where(row => row.IdKey == bb.Key).FirstOrDefault().Name;
                        doc.Words.Last.InsertAfter(Group + "\n");
                        object start1 = cur;
                        object end1 = cur + Group.Length;
                        word.Range rr = doc.Range(start1, end1);
                        rr.Italic = 1;
                        rr.Bold = 1;
                        rr.Underline = word.WdUnderline.wdUnderlineSingle;
                        cur += Group.ToString().Length + 1;

                        foreach (var bbb in bb.OrderBy(el => el.Name))
                        {

                            string name = "";
                            if (!String.IsNullOrEmpty(bbb.Name))
                            {
                                name = "Название: " + bbb.Name;
                            }
                            if (bbb.AuthorRow != null)
                            {
                                    name += " Автор: " + bbb.AuthorRow.Name;
                            }
                            string str = name + " printing: " + bbb.Printing + "\n";
                            doc.Words.Last.InsertAfter(str);
                            cur += str.Length;
                        }

                    }
                    doc.Words.Last.InsertAfter("\n");
                    cur++;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Что-то случилось... " + ex.Message + ex.StackTrace);
            }
            finally
            {
                if (doc != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
                }
                if (app != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                }
            }
        }

    
        #endregion

        #region Загрузка из базы
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            RefreshFirstsTales();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            RefreshAllTales();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            RefreshKeys();
            RefreshAut();
            RefreshFirstsTales();
        }

        private void RefreshFirstsTales()
        {
            try
            {
                ListOfTale.TalesDataSet talesDataSet = ((ListOfTale.TalesDataSet)(this.FindResource("talesDataSet")));
                groupIdColumn.ItemsSource = talesDataSet.Keys;
                authorIdColumn.ItemsSource = talesDataSet.Author;
                ListOfTale.TalesDataSetTableAdapters.TaleTableAdapter talesDataSetTaleTableAdapter = new ListOfTale.TalesDataSetTableAdapters.TaleTableAdapter();
                talesDataSetTaleTableAdapter.FillBegin(talesDataSet.Tale);
                System.Windows.Data.CollectionViewSource taleViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("taleViewSource")));
                taleViewSource.View.MoveCurrentToFirst();
                IsChanged = false;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void RefreshAllTales()
        {
            try
            {
                ListOfTale.TalesDataSet talesDataSet = ((ListOfTale.TalesDataSet)(this.FindResource("talesDataSet")));
                groupIdColumn.ItemsSource = talesDataSet.Keys;
                authorIdColumn.ItemsSource = talesDataSet.Author;
                ListOfTale.TalesDataSetTableAdapters.TaleTableAdapter talesDataSetTaleTableAdapter = new ListOfTale.TalesDataSetTableAdapters.TaleTableAdapter();
                talesDataSetTaleTableAdapter.Fill(talesDataSet.Tale);
                System.Windows.Data.CollectionViewSource taleViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("taleViewSource")));
                taleViewSource.View.MoveCurrentToFirst();
                IsChanged = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void RefreshKeys()
        {
            try
            {
                ListOfTale.TalesDataSet talesDataSet = ((ListOfTale.TalesDataSet)(this.FindResource("talesDataSet")));
                ListOfTale.TalesDataSetTableAdapters.KeysTableAdapter talesDataSetKeysTableAdapter = new ListOfTale.TalesDataSetTableAdapters.KeysTableAdapter();
                talesDataSetKeysTableAdapter.Fill(talesDataSet.Keys);
                System.Windows.Data.CollectionViewSource keysViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("keysViewSource")));
                groupIdColumn.ItemsSource = talesDataSet.Keys;
                keysViewSource.View.MoveCurrentToFirst();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void RefreshAut()
        {
            try
            {
                ListOfTale.TalesDataSet talesDataSet = ((ListOfTale.TalesDataSet)(this.FindResource("talesDataSet")));
                ListOfTale.TalesDataSetTableAdapters.AuthorTableAdapter talesDataSetAuthorTableAdapter = new ListOfTale.TalesDataSetTableAdapters.AuthorTableAdapter();
                talesDataSetAuthorTableAdapter.Fill(talesDataSet.Author);
                System.Windows.Data.CollectionViewSource authorViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("authorViewSource")));
                authorViewSource.View.MoveCurrentToFirst();
                groupIdColumn.ItemsSource = talesDataSet.Author;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #endregion

        #region быдлокод

        private void LoadFromLog()
        {
            string path = "log.txt";
            using (StreamReader sw = File.OpenText(path))
            {
                for (string str = sw.ReadLine(); !sw.EndOfStream; str = sw.ReadLine())
                {
                    try
                    {
                        Book b = new Book();
                        Regex reg = new Regex(@"\\");
                        string[] strs = reg.Split(str);
                        if (strs.Length == 5)
                        {
                            b.Name = strs[0].Trim();
                            b.Year = Convert.ToInt32(strs[1]);
                            b.Printing = strs[2].Trim();
                            b.Group = strs[3].Trim();
                        }
                        else
                        {
                            reg = new Regex(@"\s19[4-5][0-9]");
                            b.Year = Convert.ToDecimal(reg.Match(str).Value);
                            string[] strings = reg.Split(str);
                            b.Name = strings[0].Trim();
                            reg = new Regex(@"[0-9,\s]*");
                            b.Printing = reg.Match(strings[1]).Value;
                            b.Printing = b.Printing.Remove(b.Printing.Length - 1);
                            b.Group = strings[1].Remove(0, reg.Match(strings[1]).Length).Trim();


                        }
                        Books.Insert(0, b);
                    }
                    catch { }

                }

            }

        }


        private void AutLoad()
        {
            TalesDataSetTableAdapters.KeysTableAdapter ta = new TalesDataSetTableAdapters.KeysTableAdapter();
            var keys = ta.GetData().Select(r => r.Name.Trim()).ToList();
            keys.Add("зар. нар. сказка");

            TalesDataSetTableAdapters.AuthorTableAdapter at = new TalesDataSetTableAdapters.AuthorTableAdapter();
            List<string> names = at.GetData().Select(r => r.Name).ToList();
            int i =Convert.ToInt32( at.GetNewId());
            foreach (var b in Books)
            {
                if (b.Group == "все подряд")
                    continue;
                if (b.Group == "Авторская сказка")
                {
                    Regex r = new Regex(@"[А-Яа-я]+ [А-Яа-я]+\.[А-Яа-я]+.");
                    var m = r.Match(b.Name);
                    if (m.Success)
                    {
                        if (!names.Contains(m.Value.ToUpper()))
                        {
                            at.Insert("", m.Value.ToUpper(), i++);
                            names.Add(m.Value.ToUpper());
                        }
                    }
                    else
                    {
                        r = new Regex(@"[А-Яа-я]+ [А-Яа-я]+.");
                        var m2 = r.Match(b.Name);
                        if (m2.Success)
                        {
                            if (!names.Contains(m2.Value.ToUpper()))
                            {
                                at.Insert("", m2.Value.ToUpper(), i++);
                                names.Add(m2.Value.ToUpper());
                            }
                        }
                        else
                        {
                            r = new Regex("[А-Яа-я]+");
                            var m3 = r.Match(b.Name);
                            if (!names.Contains(m3.Value.ToUpper()))
                            {
                                at.Insert("", m3.Value.ToUpper(), i++);
                                names.Add(m3.Value.ToUpper());
                            }
                        }
                    }
                }
                else
                {
                    if (!keys.Contains(b.Group))
                    {
                        if (!names.Contains(b.Group.ToUpper()))
                        {
                            at.Insert("", b.Group.ToUpper(), i++);
                            names.Add(b.Group.ToUpper());
                        }
                    }
                }

            }
        }

        private void L1()
        {
            TalesDataSetTableAdapters.KeysTableAdapter ta = new TalesDataSetTableAdapters.KeysTableAdapter();
            var keys = ta.GetData().Select(r => new { Key = r.Name.Trim(), Id = r.IdKey }).ToList();
            keys.Add(new { Key = "зар. нар. сказка", Id = 4 });
            TalesDataSetTableAdapters.AuthorTableAdapter at = new TalesDataSetTableAdapters.AuthorTableAdapter();
            var ats = at.GetData().Select(row => new { Name = row.Name, Id = row.AuthorId });
            TalesDataSetTableAdapters.TaleTableAdapter tale = new TalesDataSetTableAdapters.TaleTableAdapter();
            int i =Convert.ToInt32( tale.GetNewID());
            var b1990 = Books.Where(r => r.Year == 1990).Select(r=>r).ToList();
            int kkkk = b1990.Count;
            foreach (var b in Books)
            {
                if (string.IsNullOrWhiteSpace(b.Printing))
                {
                    string[] prints = new string[1];

                    prints = new string[1];
                    prints[0] = "0";


                    if (b.Group == "все подряд")
                    {
                        foreach (var p in prints.Where(pp => pp != ""))
                        {
                            int res;
                            if (int.TryParse(p.Replace(" ", ""), out res))
                                tale.Insert(Convert.ToInt32(b.Year), 1, res, b.Name, i++, null, "");
                        }
                        continue;
                    }
                    if (b.Group == "Авторская сказка")
                    {
                        Regex r = new Regex(@"[А-Яа-я]+ [А-Яа-я]+\.[А-Яа-я]+.");
                        var m = r.Match(b.Name);
                        if (m.Success)
                        {
                            var attt = ats.Where(a => a.Name == m.Value.ToUpper()).FirstOrDefault();
                            string talename = r.Replace(b.Name, "", 1, 0);
                            foreach (var p in prints.Where(pp => pp != ""))
                            {
                                int res;
                                if (int.TryParse(p.Replace(" ", ""), out res))
                                    tale.Insert(Convert.ToInt32(b.Year), 3, res, talename, i++, attt.Id, "");
                            }
                        }
                        else
                        {
                            r = new Regex(@"[А-Яа-я]+ [А-Яа-я]+.");
                            var m2 = r.Match(b.Name);
                            if (m2.Success)
                            {
                                var attt = ats.Where(a => a.Name == m2.Value.ToUpper()).FirstOrDefault();
                                string talename = r.Replace(b.Name, "", 1, 0);
                                foreach (var p in prints.Where(pp => pp != ""))
                                {
                                    int res;
                                    if (int.TryParse(p.Replace(" ", ""), out res))
                                        tale.Insert(Convert.ToInt32(b.Year), 3, res, talename, i++, attt.Id, "");
                                }
                            }
                            else
                            {
                                r = new Regex("[А-Яа-я]+");
                                var m3 = r.Match(b.Name);
                                var attt = ats.Where(a => a.Name == m3.Value.ToUpper()).FirstOrDefault();
                                string talename = r.Replace(b.Name, "", 1, 0);
                                foreach (var p in prints.Where(pp => pp != ""))
                                {
                                    int res;
                                    if (int.TryParse(p.Replace(" ", ""), out res))
                                        tale.Insert(Convert.ToInt32(b.Year), 3, res, talename, i++, attt.Id, "");
                                }
                            }
                        }
                    }
                    else
                    {
                        if (keys.Where(k => k.Key == b.Group).FirstOrDefault() == null)
                        {
                            var attt = ats.Where(a => a.Name == b.Group.ToUpper()).FirstOrDefault();

                            foreach (var p in prints.Where(pp => pp != ""))
                            {
                                int res;
                                if (int.TryParse(p.Replace(" ", ""), out res))
                                    tale.Insert(Convert.ToInt32(b.Year), 3, res, b.Name, i++, attt.Id, "");
                            }

                        }
                        else
                        {
                            var k = keys.Where(kk => kk.Key == b.Group).FirstOrDefault();
                            if (k != null)
                            {
                                foreach (var p in prints.Where(pp => pp != ""))
                                {
                                    int res;
                                    if (int.TryParse(p.Replace(" ", ""), out res))
                                        tale.Insert(Convert.ToInt32(b.Year), k.Id, res, b.Name, i++, null, "");
                                }
                            }
                        }
                    }

                }
            }
        }
        #endregion

        #region простые обработчики
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            KeyForm kf = new KeyForm();
            kf.ShowDialog();
            RefreshKeys();
            RefreshFirstsTales();
        }

        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            AuthorForm af = new AuthorForm();
            af.ShowDialog();
            RefreshAut();
            RefreshFirstsTales();
        }
        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (MessageBox.Show("Вы уверены, что хотите завершить работу с приложением?", "", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
            {
                e.Cancel = true;
            }
        }
        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            ExportToWord();
        }

        private void taleDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            IsChanged = true;
        }
        #endregion

        private void MenuItem_Click_3(object sender, RoutedEventArgs e)
        {
            ChartViewer cv = new ChartViewer();
            cv.ShowDialog();
        }

        private void MenuItem_Click_4(object sender, RoutedEventArgs e)
        {
            SumPieChart sp = new SumPieChart();
            sp.ShowDialog();
        }

        #region Импорт из word
        private int getAuthorIdByName(string name)
        {
            TalesDataSetTableAdapters.QueriesTableAdapter qta = new TalesDataSetTableAdapters.QueriesTableAdapter();
            int? id = (int?) qta.GetGroupId(name);
            if (id.HasValue)
            {
                return -1;
            }
            TalesDataSetTableAdapters.AuthorTableAdapter ata=new TalesDataSetTableAdapters.AuthorTableAdapter();
            int? aid = (int?)qta.GetAithorId(name);
            if (aid.HasValue)
            {
                return aid.Value;
            }
            int aidr =Convert.ToInt32( ata.GetNewId());
            ata.Insert("", name.ToUpper(), aidr);
            return aidr;
        }
        private int getGroupId(string name)
        {
            TalesDataSetTableAdapters.QueriesTableAdapter qta = new TalesDataSetTableAdapters.QueriesTableAdapter();
            int? id = (int?)qta.GetGroupId(name);
            if (id.HasValue)
            {
                return id.Value;
            }
            return 3;
        }
        private void MenuItem_Click_5(object sender, RoutedEventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            if (op.ShowDialog().Value)
            {
                word.Application app = null;
                word.Document doc = null;
                try
                {
                    app = new word.Application();
                    app.Visible = false;
                    
                    doc = app.Documents.Open(op.FileName);
                    
                    int year = -1;
                    int authorId = -1;
                    int groupId = -1;

                    TalesDataSetTableAdapters.TaleTableAdapter ta = new TalesDataSetTableAdapters.TaleTableAdapter();

                    foreach (word.Paragraph p  in doc.Paragraphs)
                    {
                        string text = p.Range.Text.Replace("\r","");
                        if (String.IsNullOrWhiteSpace(text)) continue;
                        if (p.Range.Bold != 0)
                        {
                            year = Convert.ToInt32(text);
                            continue;
                        }
                        if (year == -1) continue;
                        if (p.Range.Underline==word.WdUnderline.wdUnderlineSingle||p.Range.Italic!=0)
                        {
                            groupId = getGroupId(text);
                            if (groupId == 3 && !text.ToUpper().Contains("АВТОРСКАЯ СКАЗКА"))
                                authorId = getAuthorIdByName(text);
                            else authorId = -1;
                            continue;
                        }
                        var parts = text.Split(',').ToList();

                        if (groupId == 3 && authorId == -1)
                        {

                            int auid = getAuthorIdByName(parts[0]);
                            for (int i = 1; i < parts.Count; i++)
                            {
                                string print = parts[i].Replace(" ", "").Replace("т.", "").Replace("т", "");


                                int count = 0;
                                int.TryParse(print, out count);

                                int id = Convert.ToInt32(ta.GetNewID());
                                ta.Insert(year, groupId, count, "", id, auid, "");

                            }
                        }
                        else
                        {
                            for (int i = 1; i < parts.Count; i++)
                            {
                                string print = parts[i].Replace(" ", "").Replace("т.", "").Replace("т", "");

                                int count = 0;
                                int.TryParse(print, out count);

                                int id = Convert.ToInt32(ta.GetNewID());
                                ta.Insert(year, groupId, count, parts[0], id, null, "");

                            }
                        }
                    }
                
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Что-то случилось. нужно обратиться за помощью к верховному кхыменку! " + ex.Message + ex.StackTrace);
                }
                finally
                {
                    if (doc != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
                    }
                    if (app != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                    }
                }
            }
        }
       
        #endregion

        private void MenuItem_Click_6(object sender, RoutedEventArgs e)
        {
            LoadFromLog();
            AutLoad();
            L1();
        }



        private void MenuItem_Click_8(object sender, RoutedEventArgs e)
        {
            AboutProgram ap = new AboutProgram();
            ap.ShowDialog();
        }


    }
}
